package com.gp.study.tomcat.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.gp.study.tomcat.bean.GpServletRegistry;
import com.gp.study.tomcat.http.GpRequestHandler;

public class NIOTomcat {
	
	 GpServletRegistry servletRegistry;
	 ThreadPoolExecutor threadPoolExecutor;
	 int port;
					
	public NIOTomcat(int port) {
		this.port = port;
	}

	public  void start() {
		init();
		ServerSocket server = null;
		try {
			 server = new ServerSocket(port);
			 System.out.println("gptomcat is runing at port "+port);
			 while(true){
				 Socket socket = server.accept();
				 threadPoolExecutor.execute(new GpRequestHandler(socket));
			 }
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private  void init() {
		 // 加载解析配置文件   暂时用properties文件代替
		 //注册 servlet 和   对应的处理类
		 servletRegistry = new GpServletRegistry();
		 
		 //初始化线程池
		 threadPoolExecutor = new ThreadPoolExecutor(
				 4, 
				 Runtime.getRuntime().availableProcessors()*2, 
				 3000,
				 TimeUnit.MILLISECONDS,
				 new ArrayBlockingQueue<>(300),
				 Executors.defaultThreadFactory());
		 // 后面可以设置拒绝策略
	}

}
